﻿namespace TestTool.Tests.Engine.Base.TestBase
{
    using System;
    using System.Net;
    using System.ServiceModel;
    using TestTool.HttpTransport.Interfaces;
    using TestTool.Tests.Engine.Base.Definitions;

    public abstract class BaseServiceTest<TContract, TClient> : BaseOnvifTest where TContract: class where TClient: ClientBase<TContract>, new()
    {
        private TClient _client;

        protected BaseServiceTest(TestLaunchParam param) : base(param)
        {
        }

        protected abstract TClient CreateClient();
        protected override void Initialize()
        {
            base.Initialize();
            this._client = this.CreateClient();
            ServicePointManager.Expect100Continue = false;
            base.AttachSecurity(this._client.Endpoint);
            base.SetupChannel(this._client.InnerChannel);
        }

        protected override void Release()
        {
            base.Release();
            if (this._client != null)
            {
                this._client.Close();
                this._client = default(TClient);
            }
        }

        protected void ResetBreakingBehaviour()
        {
            if (this.Client != null)
            {
                base.SetBreakingBehaviour(this.Client.Endpoint, null);
            }
        }

        protected void SetBreakingBehaviour(ISoapMessageMutator spoiler)
        {
            if (this._client != null)
            {
                base.SetBreakingBehaviour(this.Client.Endpoint, spoiler);
            }
        }

        protected void UpdateSecurity()
        {
            if (this._client != null)
            {
                this._client.Close();
            }
            this._client = this.CreateClient();
            ServicePointManager.Expect100Continue = false;
            base.AttachSecurity(this._client.Endpoint);
            base.SetupChannel(this._client.InnerChannel);
        }

        protected TClient Client
        {
            get
            {
                return this._client;
            }
        }
    }
}

